package com.yan.activity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;

import com.yan.R;

public class ArticlesListManager{
	
	private static final String TAG = "ARTICLES_LIST_MANAGER";
	protected Handler mHandler;
	protected DataManager mDataManager;
	protected Context mContext;
	private View mArticlesListView;
	private ListView mArticlesList;
	private ArticlesListAdapter mArticlesListAdapter;
	
	
	public ArticlesListManager(Context context, View view)
	{
		
		mHandler = new Handler();
		mDataManager = DataManager.getInstance();
		mContext = context;
		mArticlesListAdapter= null;
		
		initView(view);
        new InitAsyncTask().execute();

	}
	
	public void initArticles()
	{
		if(mArticlesListAdapter == null)
		{
			mArticlesListAdapter = new ArticlesListAdapter(mContext, mDataManager.getArticles(), R.layout.article_list_element);	
		}
		else
		{
			showArticlesList();

		}
	}




	private void initView(View view) 
	{
		mArticlesListView = view;
		mArticlesList = (ListView) mArticlesListView.findViewById(R.id.articles_listview);
		mArticlesList.setDividerHeight(0);

		//mArticlesList.setEmptyView(mArticlesListView.findViewById(R.id.empty));
	
	}

	public void showArticlesList()
	{
		mHandler.post(new Runnable()
		{
			public void run()
			{
				mArticlesList.setAdapter(mArticlesListAdapter);
				mArticlesList.setOnItemClickListener(mArticlesListAdapter);
			}
		});
	}

	
	
	
	/**
	 * 
	 * ASYNC TASK
	 * 
	 */
	
	private class InitAsyncTask extends AsyncTask<Void, Void, Void>{
		@Override
		public Void doInBackground(Void...notUsed){
		
			initArticles();
			return null;
		}
		
		@Override
		public void onPostExecute(Void notUsed){
			showArticlesList();

				Debug.getCurrentTimeMeasure(true);
		
	}
		
	}

	

}
